<template>
  <el-dialog v-model="visible" :title="title" width="480px" append-to-body>
    <div v-if="freq === 'qd'" class="panel">
      <el-form :model="formTid" label-width="84px" class="form-panel">
        <el-form-item label="第1次">
          <el-time-picker v-model="formTimes[0]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="freq === 'bid'" class="panel">
      <el-form :model="formTid" label-width="84px" class="form-panel">
        <el-form-item label="第1次">
          <el-time-picker v-model="formTimes[0]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
        <el-form-item label="第2次">
          <el-time-picker v-model="formTimes[1]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="freq === 'tid'" class="panel">
      <el-form :model="formTid" label-width="84px" class="form-panel">
        <el-form-item label="第1次">
          <el-time-picker v-model="formTimes[0]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
        <el-form-item label="第2次">
          <el-time-picker v-model="formTimes[1]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
        <el-form-item label="第3次">
          <el-time-picker v-model="formTimes[2]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="freq === 'qid'" class="panel">
      <el-form :model="formTid" label-width="84px" class="form-panel">
        <el-form-item label="第1次">
          <el-time-picker v-model="formTimes[0]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
        <el-form-item label="第2次">
          <el-time-picker v-model="formTimes[1]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
        <el-form-item label="第3次">
          <el-time-picker v-model="formTimes[2]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
        <el-form-item label="第4次">
          <el-time-picker v-model="formTimes[3]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="freq === 'qod'" class="panel">
      <el-form :model="formTid" label-width="84px" class="form-panel">
        <el-form-item label="第1次">
          <el-time-picker v-model="formTimes[0]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="freq === 'qw'" class="panel">
      <el-form :model="formBiw" label-width="84px" class="form-panel">
        <el-form-item label="第1次">
          <div class="row">
            <el-select v-model="formTimes[0]" placeholder="选择星期" style="width: 120px">
              <el-option v-for="w in weekdays" :key="w" :label="w" :value="w" />
            </el-select>
            <el-time-picker v-model="formTimes[1]" format="HH:mm" value-format="HH:mm" />
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="freq === 'biw'" class="panel">
      <el-form :model="formBiw" label-width="84px" class="form-panel">
        <el-form-item label="第1次">
          <div class="row">
            <el-select v-model="formTimes[0][0]" placeholder="选择星期" style="width: 120px">
              <el-option v-for="w in weekdays" :key="w" :label="w" :value="w" />
            </el-select>
            <el-time-picker v-model="formTimes[0][1]" format="HH:mm" value-format="HH:mm" />
          </div>
        </el-form-item>
        <el-form-item label="第2次">
          <div class="row">
            <el-select v-model="formTimes[1][0]" placeholder="选择星期" style="width: 120px">
              <el-option v-for="w in weekdays" :key="w" :label="w" :value="w" />
            </el-select>
            <el-time-picker v-model="formTimes[1][1]" format="HH:mm" value-format="HH:mm" />
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="freq === 'hs'" class="panel">
      <el-form :model="formTid" label-width="84px" class="form-panel">
        <el-form-item label="第1次">
          <el-time-picker v-model="formTimes[0]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="freq === 'qn'" class="panel">
      <el-form :model="formTid" label-width="84px" class="form-panel">
        <el-form-item label="第1次">
          <el-time-picker v-model="formTimes[0]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="freq === 'qnd'">
      <el-form :model="formTid" label-width="84px" class="form-panel">
        <el-form-item label="第1次">
          <el-time-picker v-model="formTimes[0]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="freq === 'qnw'">
      <el-form :model="formBiw" label-width="84px" class="form-panel">
        <el-form-item label="第1次">
          <div class="row">
            <el-select v-model="formTimes[0]" placeholder="选择星期" style="width: 120px">
              <el-option v-for="w in weekdays" :key="w" :label="w" :value="w" />
            </el-select>
            <el-time-picker v-model="formTimes[1]" format="HH:mm" value-format="HH:mm" />
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="freq === 'nid'" class="panel">
      <el-form :model="formNid" label-width="84px" class="form-panel">
        <el-form-item label="每天从">
          <el-time-picker v-model="formTimes[0]" format="HH:mm" value-format="HH:mm" />
          <span class="helper">开始，至</span>
          <el-time-picker v-model="formTimes[1]" format="HH:mm" value-format="HH:mm" />
          <span class="helper">结束</span>
        </el-form-item>
        <div class="hint">按执行次数均分时间段</div>
      </el-form>
    </div>
    <div v-if="freq === '1日1次'" class="panel">
      <el-form :model="formTid" label-width="84px" class="form-panel">
        <el-form-item label="第1次">
          <el-time-picker v-model="formTimes[0]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="freq === '1日2次'" class="panel">
      <el-form :model="formTid" label-width="84px" class="form-panel">
        <el-form-item label="第1次">
          <el-time-picker v-model="formTimes[0]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
        <el-form-item label="第2次">
          <el-time-picker v-model="formTimes[1]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="freq === '1日3次'" class="panel">
      <el-form :model="formTid" label-width="84px" class="form-panel">
        <el-form-item label="第1次">
          <el-time-picker v-model="formTimes[0]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
        <el-form-item label="第2次">
          <el-time-picker v-model="formTimes[1]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
        <el-form-item label="第3次">
          <el-time-picker v-model="formTimes[2]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="freq === '1日4次'" class="panel">
      <el-form :model="formTid" label-width="84px" class="form-panel">
        <el-form-item label="第1次">
          <el-time-picker v-model="formTimes[0]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
        <el-form-item label="第2次">
          <el-time-picker v-model="formTimes[1]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
        <el-form-item label="第3次">
          <el-time-picker v-model="formTimes[2]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
        <el-form-item label="第4次">
          <el-time-picker v-model="formTimes[3]" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup name="ExecTimeConfigDialog">
import { computed, reactive, watch } from 'vue'

// 可见性与记录数据由父组件传入
const props = defineProps({
  visible: { type: Boolean, default: false },
  record: { type: Object, default: () => ({}) }
})
const emit = defineEmits(['update:visible', 'save'])

// 标题与频率
const freq = computed(() => props.record?.frequencyCode || '')
const title = computed(() => {
  if (freq.value === 'qd') return 'qd，每天执行时间'
  if (freq.value === 'bid') return 'bid，每天执行时间'
  if (freq.value === 'tid') return 'tid，每天执行时间'
  if (freq.value === 'qid') return 'qid，每天执行时间'
  if (freq.value === 'qod') return 'qod，隔日执行时间'
  if (freq.value === 'qw') return 'qw，每周执行时间'
  if (freq.value === 'biw') return 'biw，每周执行时间'
  if (freq.value === 'hs') return 'hs，临睡前执行时间'
  if (freq.value === 'qn') return 'qn，每晚执行时间'
  if (freq.value === 'qnd') return 'qnd，n天执行时间'
  if (freq.value === 'qnw') return 'qnw，n周执行时间'
  if (freq.value === 'nid') return 'nid，每天执行时间'
  if (freq.value === '1日1次') return '1日1次，每天执行时间'
  if (freq.value === '1日2次') return '1日2次，每天执行时间'
  if (freq.value === '1日3次') return '1日3次，每天执行时间'
  if (freq.value === '1日4次') return '1日4次，每天执行时间'
  return '执行时间配置'
})

// 可见性双向绑定
const visible = computed({
  get: () => props.visible,
  set: v => emit('update:visible', v)
})

// 星期选项与排序
const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
const weekdayOrder = w => weekdays.indexOf(w)

// 本地状态
const formTimes = ref([])

// 解析 timesText 预填表单
watch(
  () => props.record,
  r => {
    if (!r.defaultExecutionTimeValue) return
    const timeValue = JSON.parse(r.defaultExecutionTimeValue)
    formTimes.value = timeValue
    console.log('修改传入', r, timeValue)
  },
  { immediate: true }
)

// timesText 生成
function formatTimesText(freq, params) {
  if (['qd', 'bid', 'tid', 'qid', '1日1次', '1日2次', '1日3次', '1日4次'].includes(freq)) {
    const times = [...params.times].sort((a, b) => a.localeCompare(b))
    return `每天 ${times.join(',')}`
  }
  if (['qw', 'biw'].includes(freq)) {
    const ordered = [...params.pairs].sort(
      (a, b) => weekdayOrder(a.weekday) - weekdayOrder(b.weekday) || a.time.localeCompare(b.time)
    )
    return ordered.map(p => `每周${p.weekday} ${p.time}`).join(',')
  }
  if (freq === 'nid') {
    return `从第${params.start}开始到${params.end}结束，按次数均分时间段`
  }
  if (freq === 'st') return '立即执行'
  return ''
}

// 校验逻辑（依据上方不同freq的面板字段进行严格校验）
function validate() {
  // 每日/隔日/每晚/睡前/每n天/中药：需要填写指定数量的时间点
  const needTimesCountMap = {
    qd: 1,
    qod: 1,
    hs: 1,
    qn: 1,
    qnd: 1,
    '1日1次': 1,
    bid: 2,
    '1日2次': 2,
    tid: 3,
    '1日3次': 3,
    qid: 4,
    '1日4次': 4
  }
  if (freq.value in needTimesCountMap) {
    // 过滤空值并校验数量是否满足要求
    const filled = formTimes.value.filter(Boolean)
    const need = needTimesCountMap[freq.value]
    if (filled.length !== need) return `请完整填写${need}次执行时间`
    return null
  }

  // 每周一次：需填写一行 星期+时间
  if (freq.value === 'qw') {
    const p = formTimes.value[0]
    if (!p[0] || !p[1]) return '请填写每周一次的星期与时间'
    return null
  }

  // 每周两次：需填写两行 星期+时间
  if (freq.value === 'biw') {
    const p1 = formTimes.value[0]
    const p2 = formTimes.value[1]
    if (!p1[0] || !p1[1] || !p2[0] || !p2[1]) return '请完整填写每周两次的星期与时间'
    return null
  }

  // 每n周一次：需填写一行 星期+时间
  if (freq.value === 'qnw') {
    const p = formTimes.value
    if (!p[0] || !p[1]) return '请填写每n周一次的星期与时间'
    return null
  }

  // 每天n次：需填写开始与结束时间，且开始早于结束
  if (freq.value === 'nid') {
    if (!formTimes.value[0] || !formTimes.value[1]) return '请填写开始与结束时间'
    if (formTimes.value[0] >= formTimes.value[1]) return '开始时间必须早于结束时间'
    return null
  }

  // 其他情况（如st：立即执行）不需要校验
  return null
}

// 取消与确定
function handleCancel() {
  visible.value = false
}
function handleConfirm() {
  const msg = validate()
  if (msg) return emit('save', { error: msg })
  emit('save', {
    id: props.record.id,
    tenantId: props.record.tenantId,
    frequencyCode: freq.value,
    defaultExecutionTimeValue: formTimes.value
  })
  visible.value = false
}
</script>

<style scoped>
.panel {
  padding: 4px 2px;
}
.row {
  display: inline-flex;
  align-items: center;
  gap: 10px;
}
.helper {
  margin: 0 6px;
  color: var(--el-text-color-secondary);
}
.hint {
  margin-left: 6px;
  color: var(--el-text-color-secondary);
}
.form-panel {
  :deep(.el-form-item__label) {
    border: 1px solid var(--el-border-color);
  }
  :deep(.el-form-item__content) {
    border: 1px solid var(--el-border-color);
    border-left: none;
  }
  :deep(.el-select__wrapper) {
    box-shadow: none !important;
  }
  :deep(.el-input__wrapper) {
    border: 1px solid var(--el-border-color);
  }
}
</style>
